#! /usr/bin/env python
# -*- coding: UTF-8 -*-
"""
Created by jianbing on 2017-09-08
"""
import os
import shutil
import time
from jinja2 import FileSystemLoader
from jinja2.environment import Environment

current_dir = os.path.dirname(__file__)


class _BaseReport:
    def __init__(self, template_file):
        self._template_file = template_file
        self._data = dict()

    def preview_report(self):
        """预览测试报告内容

        :return:
        """
        print(self._render_report())

    def _render_report(self):
        env = Environment()
        env.loader = FileSystemLoader(os.path.join(current_dir, 'template'))
        template = env.get_template(self._template_file)
        return template.render(**self._data)

    def save(self):
        """保存测试报告文件

        :return:
        """
        report_dir = os.path.join(current_dir, "result",
                                  time.strftime("%Y-%m-%d-%H-%M-%S", time.localtime(time.time())))

        if not os.path.exists(report_dir):
            os.makedirs(report_dir)

        shutil.copytree(os.path.join(current_dir, r"template\static"), r"{}\static".format(report_dir))

        with open(r"{}\report.html".format(report_dir), 'w', encoding='utf-8') as f:
            f.write(self._render_report())

        print("报告已经生成")
        os.system("start {}".format(report_dir))


class SimpleReport(_BaseReport):
    def __init__(self):
        super().__init__(template_file="simple_report.html")
        self._charts = []

    def set_title(self, title):
        self._data["title"] = title

    def set_summary(self, summary):
        self._data["summary"] = [i for i in summary.splitlines() if i]

    def add_chart(self, chart):
        self._charts.append(chart)

    def save(self):
        render_charts = []
        for index, chart in enumerate(self._charts):
            render_charts.append(chart.render())

        self._data["charts"] = render_charts

        super().save()


class CustomReport(_BaseReport):
    def __init__(self, template_file=None):
        super().__init__(template_file)

    def load_template(self, template_file):
        self._template_file = template_file

    def fill_data(self, **kwargs):
        self._data.update(**kwargs)

    def save(self):
        if not self._template_file:
            raise Exception("需要调用load_template，配置模板")
        super().save()
